package com.example.socket_client_demo;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import com.uwantsoft.goeasy.client.service.AbstractGoEasyReceiver;

import java.util.List;

/**
 * @author Chuanbao
 */
public class GoEasyMessageReceiver extends AbstractGoEasyReceiver {

    @Override
    public void onMessageReceived(Context context, String channel, String content) {
        if(!isRunningForeground(context)){
            sendNotification(context, content);
        }
    }

    private void sendNotification(Context context, String content) {
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent = new Intent(context, MyActivity.class);
        intent.putExtra("content", content);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notify1 = new Notification();
        notify1.icon = R.drawable.ic_launcher;
        notify1.tickerText = "您有来自GoEasy的新消息，请注意查收！";
        notify1.when = System.currentTimeMillis();
        notify1.setLatestEventInfo(context, "GoEasy 新消息",
                "点击查看新消息", pendingIntent);
        notify1.defaults=Notification.DEFAULT_SOUND;
        notify1.number = 1;
        notify1.flags |= Notification.FLAG_AUTO_CANCEL;
        manager.notify(1, notify1);
    }
//    private boolean isForeground(Context context, String className){
//        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
//        if (list != null && list.size() > 0) {
//            ComponentName cpn = list.get(0).topActivity;
//            if (className.equals(cpn.getClassName())) {
//                return true;
//            }
//        }
//        return false;
//    }


    private boolean isRunningForeground (Context context)
    {
        ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if(!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName()))
        {
            return true ;
        }

        return false ;
    }
}
